package com.sun.kafka.config;

import com.sun.kafka.properties.ThreadPoolProperty;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * 线程池配置
 */
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ThreadPoolConfig {

    private final ThreadPoolProperty threadPoolProperty;

    @Bean(name = "threadPoolExecutor")
    public ThreadPoolExecutor getThreadPoolExecutor() {
        return new ThreadPoolExecutor(threadPoolProperty.getCorePoolSize(),
                threadPoolProperty.getMaxPoolSize(),
                threadPoolProperty.getKeepAliveTime(),
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(threadPoolProperty.getQueueSize()),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("my-thread-" + UUID.randomUUID());
                    return thread;
                },
                (r, e) -> {
                    throw new RejectedExecutionException("线程池已满");
                });
    }

}
